package at.fhv.components.laplace;

import java.awt.image.renderable.ParameterBlock;

import javax.media.jai.JAI;
import javax.media.jai.KernelJAI;
import javax.media.jai.PlanarImage;

import at.fhv.framework.CommonImageProcessingHelper;
import at.fhv.framework.events.ImageEvent;
import at.fhv.framework.listeners.ImageProcessingListener;
import at.fhv.framework.listeners.RefireListener;

/**
 * The ImagePanel class.
 * 
 * @author Michael Sieber
 */
public class LaplaceFilter implements ImageProcessingListener, RefireListener
{
	private CommonImageProcessingHelper _helper;
	private PlanarImage _image;
	private Laplace _laplace;

	/**
	 * Create a new ImagePanel
	 */
	public LaplaceFilter() {
		_helper = new CommonImageProcessingHelper(this);
		_laplace = Laplace.LAPLACE_1;
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void imageChanged(ImageEvent event) {
		_image = event.getImage();
		execute();
	}

	public void execute() {
		if (_image != null) {
			KernelJAI kernel = new KernelJAI(3, 3, _laplace.getMatrix());

			ParameterBlock pb = new ParameterBlock();
			pb.addSource(_image);
			pb.add(kernel);

			_image = JAI.create("convolve", pb);
			_helper.fireImageProcessingEvent(new ImageEvent(this, _image));
		}
	}

	/**
	 * @return The sobel
	 */
	public Laplace getLaplace() {
		return _laplace;
	}

	/**
	 * @param laplace The sobel to set
	 */
	public void setLaplace(Laplace laplace) {
		_laplace = laplace;
		_helper.fireRefireEvent();
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void addRefireListener(RefireListener listener) {
		_helper.addRefireListener(listener);
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void removeRefireListener(RefireListener listener) {
		_helper.removeRefireListener(listener);
	}

	/*
	 * {@inheritDoc}
	 */
	@Override
	public void refire() {
		_helper.fireImageProcessingEvent(new ImageEvent(this, _image));
	}

	/**
	 * Add an image change listener
	 * 
	 * @param listener The image change listener to add
	 */
	public void addImageChangeListener(ImageProcessingListener listener) {
		_helper.addImageProcessingListener(listener);

		// force all previous beans to refire their event
		_helper.fireRefireEvent();
	}

	/**
	 * Remove an image change listener
	 * 
	 * @param listener The image change listener to remove
	 */
	public void removeImageChangeListener(ImageProcessingListener listener) {
		_helper.removeImageProcessingListener(listener);
	}

}
